package com.yuqian.JavaSe.leetcode.easy;
/**
 * Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.
 * @author yuqian
 *
 *讲罗马数字转换为数字
 */
public class RomantoInteger {
    public static int romanToInt(String s) {
    	int[] sizes = {1, 5, 10, 50, 100, 500, 1000};
        char[] symbols = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
        
        int i, j, k;
        
        i = s.length() - 1;
        j = 0;
        k = 0;
        int result = 0;
        while (i >= 0) {
            if (s.charAt(i) == symbols[j]) {
                result += sizes[j];
                i--;
            } else if (j > 0 && s.charAt(i) == symbols[k]) {
                result -= sizes[k];
                i--;
            } else {
                j++;
                k = j % 2 == 0 ? j - 2 : j - 1;
            }
        }
        return result; 
    }
    
    public static void main(String[] args) {
	System.out.println(romanToInt("MCMXCVI"));	
	}
}
